package com.jky.stmall.manger.mapper;

import com.jky.stmall.manger.entity.Category;
import org.apache.ibatis.annotations.*;

import java.util.List;

/*
* Mapper层的接口
* 基于注解的开发
* */
@Mapper //Mybatis的注解，当前的接口是Mybatis的接口。相当于Application添加MapperScan
public interface CategoryMapper {
/*
* 插入 数据表的操作
* 1.返回值类型 int
* 2.方法名 insert
* 3.参数 category
* 4.配置
* */
    @Insert({"insert into category",
    "(name, dscp, pic, parent_id, recom)",
    "value(#{name},#{dscp},#{pic},#{parentId},#{recom})",
    })
    //获取添加id
    @Options(useGeneratedKeys = true,keyColumn = "id",keyProperty = "id")
    int insert (Category category);
    /**
     * 根据ID删除
     */
    @Delete("delete from category where id= #{id}")
    int delete(Integer id);
    /**
     * 根据ID更新 使用动态sql  属性存在的时候才更新。 script 为了使其有效
     */
    @Update({"<script>",
            "update category",
            "<set>",
            "<if test='name!=null and name.length>0'> name=#{name},</if>",
            "<if test='dscp!=null and dscp.length>0'> dscp=#{dscp},</if>",
            "<if test='pic!=null and pic.length>0'> pic=#{pic},</if>",
            //判断参数parentId属性不为空
            //设置数据表的parent_id字段 为参数属性
            "<if test='parentId!=null'> parent_id=#{parentId},</if>",
            "<if test='recom!=null'> recom=#{recom}</if>",
            "</set>",
            "where id =#{id}",
            "</script>"
    })
    int update(Category category);
    /**
     * 根据ID查询
     */
    @Select("select * from category where id=#{id}")
    Category selectById(Integer id);
    /**
     * 组合查询
     */
    @Select({"<script>",
            "select * from category",
            "<where>",
            "<if test='name!=null and name.length>0'>name like '%${name}%'</if>",
            "<if test='parentId!=null and parentId!=0'> and parent_id=#{parentId}</if>",
            "<if test='parentId!=null and parentId==0'>and parent_id is null</if>",
            "<if test='recom!=null'>and recom=#{recom} </if>",
            "<if test='status!=null'>and status=#{status} </if>",
            "</where>",
            "</script>"
    })

    @Results({
            //相当于<resultMap>的标签
            @Result(column = "parent_id",property ="parentId"),//重新映射  找回 id
            @Result(column = "parent_id",property = "parent",
            one = @One(select = "selectById"))//相当于<id> <result>标签
    })
    List<Category> select(Category category);
}
